import React, { useState, useEffect } from "react";
import Taro, { getCurrentInstance } from "@tarojs/taro";
import { View, Text } from "@tarojs/components";
import { wxLogin } from "./api";

export default function Index() {
  const [msg, setMsg] = useState("");
  useEffect(() => {
    Taro.getStorage({
      key: "userInfo",
      success: function (res) {
        Taro.switchTab({ url: "index/index" });
      },
      fail: function (err) {
        Taro.showModal({
          title: "提示",
          content: "请先授权登录",
          success: (res) => {
            if (res.confirm) {
              Taro.login({
                success: function (res) {
                  console.log(res.code);
                  wxLogin(res.code).then((r) => {
                    console.log(r);
                    if (r.code === 200) {
                      // 微信团队抛弃了wx.getUserInfo、wx.getUserProfile接口
                      // 获取用户头像将统一返回默认灰色头像，昵称将统一返回 “微信用户”
                      // Taro.getUserInfo({
                      //   success: function (res) {
                      //     console.log(res.userInfo);
                      //   }
                      // })
                      Taro.setStorage({
                        key: "userInfo",
                        data: r.data,
                      });
                      Taro.switchTab({ url: "index/index" });
                    }
                  });
                },
              });
            } else if (res.cancel) {
              console.log("cancel");
              setMsg("取消授权，登录失败");
            }
          },
          failure: (err) => {
            setMsg("授权失败");
          },
        });
      },
    });
  }, []);

  const style = {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    alignContent: "center",
    height: "100vh",
    fontWeight: "bold",
  };

  return <View style={style}>{msg}</View>;
}
